import React, { useState, useEffect } from 'react';
import './packPage.css';
import Header from '../Header/Header';
import PackFailureModal from '../../components/PackFailureModal/PackFailureModal';
import ApiService from '../../api/index';

import cc2026Img from '../../assets/login/cc2026.png';
// 导入 fjyj.png 作为背景图片
import fjyjImg from '../../assets/login/fjyj.png';
// 导入 xzbjt.png 图片
import xzbjtImg from '../../assets/login/xzbjt.png';
// 导入 hshs.png 图片作为图标背景
import iconBackImg from '../../assets/icon/icon-back.png';
// 导入 close.png 图片作为关闭按钮
import closeImg from '../../assets/login/close.png';
// 导入 xy.png 图片作为弹框背景
import xyImg from '../../assets/icon/tk-cw.png';
// 导入 dbxl-back.png 图片作为打包行李弹框背景
import dbxlBackImg from '../../assets/icon/dbxl-back.png';

// 导入 bz.png 图片
import bzImg from '../../assets/icon/bz.png';
// 导入 gx.png 作为勾选图标
import gxImg from '../../assets/login/gx.png';

// 导入所有图标图片
import hshsImg from '../../assets/icon/hshs.png';
import gskhImg from '../../assets/icon/gskh.png';
import hyllImg from '../../assets/icon/hyll.png';
import bbgsImg from '../../assets/icon/bbgs.png';
import ssryImg from '../../assets/icon/ssry.png';
import myflImg from '../../assets/icon/myfl.png';
import jzjlImg from '../../assets/icon/jzjl.png';
import szjxImg from '../../assets/icon/szjx.png';
import jyczImg from '../../assets/icon/jycz.png';
import hwylImg from '../../assets/icon/hwyl.png';
import jbaxImg from '../../assets/icon/jbax.png';
import thggImg from '../../assets/icon/thgg.png';
import ylghImg from '../../assets/icon/ylgh.png';
import plrsImg from '../../assets/icon/plrs.png';
import nnyyImg from '../../assets/icon/nnyy.png';
import cwImg from '../../assets/icon/cw.png';

/**
 * 图标和文字数据数组
 * 包含15个图标的图片和对应的文字描述
 */
const imagesText = [{
  id: 1,
  img: hshsImg,
  text: '好事"花生"',
}, {
  id: 2,
  img: gskhImg,
  text: '杠上开"发"',
}, {
  id: 3,
  img: hyllImg,
  text: '好运"莲连"',
}, {
  id: 4,
  img: bbgsImg,
  text: '步步高升',
}, {
  id: 5,
  img: ssryImg,
  text: '"柿柿"如意',
}, {
  id: 6,
  img: myflImg,
  text: '"莓"有烦恼',
}, {
  id: 7,
  img: jzjlImg,
  text: '禁止"蕉"绿',
}, {
  id: 8,
  img: szjxImg,
  text: '升职加薪',
}, {
  id: 9,
  img: jyczImg,
  text: '教育成长',
}, {
  id: 10,
  img: hwylImg,
  text: '毫无"鸭梨"',
}, {
  id: 11,
  img: jbaxImg,
  text: '"家"倍安心',
}, {
  id: 12,
  img: thggImg,
  text: '"桃花"滚滚',
}, {
  id: 13,
  img: ylghImg,
  text: '养老规划',
}, {
  id: 14,
  img: plrsImg,
  text: '"票"亮人生',
}, {
  id: 15,
  img: nnyyImg,
  text: '年年有"鱼"',
}]



/**
 * FjyjPage 页面组件类
 * 功能：使用 fjyj.png 作为背景图片，显示xzbjt图片
 * 成员变量：touchStartY, touchEndY
 * 成员函数：滑动检测、页面切换等
 */
const FjyjPage = ({ onBack, onNextPage, onGoToTextPage }) => {
  // 滑动检测状态
  const [touchStartY, setTouchStartY] = useState(0);
  const [touchEndY, setTouchEndY] = useState(0);

  // 选择状态管理
  const [selectedItems, setSelectedItems] = useState([]);

  // 弹框显示状态管理
  const [showPackModal, setShowPackModal] = useState(false);
  // 打包失败弹框显示状态管理
  const [showPackFailureModal, setShowPackFailureModal] = useState(false);
  // 超出选择限制弹框显示状态管理
  const [showExceedLimitModal, setShowExceedLimitModal] = useState(false);

  // 猜行李相关状态
  const [luggageData, setLuggageData] = useState(null);
  const [isGuessMode, setIsGuessMode] = useState(false);
  const [shareUserId, setShareUserId] = useState(null);
  const [userOpenId, setUserOpenId] = useState(null);

  // 物品列表数据状态
  const [itemsData, setItemsData] = useState([]);
  const [isLoadingItems, setIsLoadingItems] = useState(true);

  /**
   * 组件初始化时检查是否为猜行李模式并获取物品数据
   */
  useEffect(() => {
    // 直接从URL获取userId，避免URLSearchParams的自动解码
    const urlString = window.location.search;
    const userIdMatch = urlString.match(/[?&]userId=([^&]*)/);
    const userId = userIdMatch ? decodeURIComponent(userIdMatch[1]) : null;
    const openId = localStorage.getItem('openId');

    console.log('页面初始化 - URL参数检查:');
    console.log('完整URL:', window.location.href);
    console.log('userId:', userId);
    console.log('openId:', openId);

    // 如果URL中有userId，保存到localStorage
    if (userId && userId !== "" && userId !== "null") {
      localStorage.setItem('userId', userId);
      console.log('保存userId到localStorage:', userId);
    }

    if (userId && userId !== "") {
      console.log('检测到userId，进入猜行李模式');
      setShareUserId(userId);
      setIsGuessMode(true);
      setUserOpenId(openId);
    } else {
      console.log('未检测到userId，进入正常模式');
      // 正常模式下，从 localStorage 获取当前用户的 openId
      let localOpenId = localStorage.getItem('openId');
      let localUserId = localStorage.getItem('userId');

      // 如果没有 openId，强制设置一个
      if (!localOpenId || localOpenId === '' || localOpenId === 'null') {
        localOpenId = 'default_openid_' + Date.now();
        localStorage.setItem('openId', localOpenId);
        console.log('强制设置 openId:', localOpenId);
      }

      // 如果没有 userId，强制设置一个
      if (!localUserId || localUserId === '' || localUserId === 'null') {
        localUserId = 'default_userid_' + Date.now();
        localStorage.setItem('userId', localUserId);
        console.log('强制设置 userId:', localUserId);
      }

      console.log('从localStorage获取 - openId:', localOpenId, 'userId:', localUserId);
      setUserOpenId(localOpenId);
    }

    // 获取物品列表数据
    fetchItemsData();
  }, []);

  /**
   * 获取物品列表数据
   */
  const fetchItemsData = async () => {
    try {
      setIsLoadingItems(true);
      console.log('开始调用 getLuggageListData 接口');
      const response = await ApiService.luggage.getLuggageListData({ page: 1, limit: 15 });
      console.log('getLuggageListData 接口响应:', response);

      if (response.data) {
        console.log('设置itemsData为接口数据:', response.data);
        setItemsData(response.data);
      } else if (response && Array.isArray(response)) {
        console.log('设置itemsData为直接数组:', response);
        setItemsData(response);
      } else {
        console.log('接口数据格式异常，使用静态数据');
        setItemsData(imagesText);
      }
    } catch (error) {
      console.error('获取物品列表数据失败:', error);
      // 如果接口失败，使用原有的静态数据作为备用
      console.log('接口调用失败，使用静态数据作为备用');
      setItemsData(imagesText);
    } finally {
      setIsLoadingItems(false);
    }
  };

  /**
   * 提交猜行李结果
   */
  const submitGuessResult = async () => {
    console.log('开始执行 submitGuessResult');

    // 从localStorage获取保存的userId
    const cachedUserId = localStorage.getItem('userId');
    const finalUserId = shareUserId || cachedUserId;

    console.log('当前参数: shareUserId:', shareUserId, 'cachedUserId:', cachedUserId, 'finalUserId:', finalUserId, 'userOpenId:', userOpenId, 'selectedItems:', selectedItems);

    if (!finalUserId || !userOpenId || selectedItems.length !== 5) {
      console.error('提交猜测结果失败: 参数不完整', {
        finalUserId: !!finalUserId,
        userOpenId: !!userOpenId,
        selectedItemsLength: selectedItems.length
      });
      return;
    }

    // 获取选中物品的ID列表
    console.log('selectedItems:', selectedItems);
    console.log('itemsData:', itemsData);

    const selectedBaggageIds = selectedItems.map(index => {
      const item = itemsData[index];
      console.log(`索引${index}对应的物品:`, item);
      if (!item) {
        console.warn(`索引${index}没有对应的物品数据`);
        return null;
      }
      if (!item.id) {
        console.warn(`索引${index}的物品缺少ID:`, item);
        return null;
      }
      console.log(`索引${index}的物品ID:`, item.id);
      return item.id;
    }).filter(id => id !== null);

    console.log('筛选后的ID数组:', selectedBaggageIds);
    const finalBaggageIds = selectedBaggageIds.join(',');
    console.log('最终的guessedBaggageIds:', finalBaggageIds);

    // 计算默契度得分 (简单示例，可根据实际业务逻辑调整)
    const matchScore = calculateMatchScore();
    console.log('计算的默契度得分:', matchScore);

    const guessData = {
      guessedBaggageIds: finalBaggageIds,
      matchScore: matchScore,
      openId: userOpenId,
      userId: finalUserId
    };
    console.log('准备提交的数据:', guessData);
    console.log('guessData.openId:', guessData.openId);

    try {
      console.log('开始调用 API: ApiService.luggage.getLuggageByUserId');
      const response = await ApiService.luggage.getLuggageByUserId(guessData);
      console.log('API响应:', response);
      if (onGoToTextPage) {
        onGoToTextPage();
      }
    } catch (error) {
      console.error('提交猜测结果失败:', error);
      alert('提交失败，请检查网络连接');
    }
  };

  /**
   * 计算默契度得分
   * @returns {number} 默契度得分
   */
  const calculateMatchScore = () => {
    if (!luggageData || !luggageData.baggageIds) {
      console.log('没有原始行李数据，默契度设为0');
      return 0;
    }

    // 获取原始选择的行李ID列表
    const originalBaggageIds = luggageData.baggageIds.split(',').map(id => id.trim());

    // 获取当前选择的行李ID列表
    const currentBaggageIds = selectedItems.map(index => {
      const item = itemsData[index];
      return item && item.id ? String(item.id) : null;
    }).filter(id => id !== null);

    console.log('原始选择的行李IDs:', originalBaggageIds);
    console.log('当前选择的行李IDs:', currentBaggageIds);

    // 计算匹配的数量
    const matchCount = currentBaggageIds.filter(id => originalBaggageIds.includes(id)).length;
    const score = Math.round((matchCount / 5) * 100);

    console.log('匹配数量:', matchCount, '默契度得分:', score);
    return score;
  };


  /**
   * 打包行李弹框关闭处理函数
   * 功能：关闭打包行李弹框
   * 参数：无
   * 返回值：无
   */
  const handlePackModalClose = () => {
    setShowPackModal(false);
  };

  /**
   * 打包失败弹框关闭处理函数
   * 功能：关闭打包失败弹框
   * 参数：无
   * 返回值：无
   */
  const handlePackFailureModalClose = () => {
    setShowPackFailureModal(false);
  };

  /**
   * 图标点击处理函数
   * 功能：切换图标的选择状态，限制最多选择5个
   * 参数：index - 图标索引
   * 返回值：无
   */
  const handleIconClick = (index) => {
    setSelectedItems(prev => {
      const isSelected = prev.includes(index);
      let newSelectedItems;

      if (isSelected) {
        // 如果已选中，则取消选择
        newSelectedItems = prev.filter(item => item !== index);
      } else {
        // 如果未选中且未达到最大选择数量，则添加选择
        if (prev.length < 5) {
          newSelectedItems = [...prev, index];
        } else {
          // 已选择5个，弹出提示
          setTimeout(() => {
            setShowExceedLimitModal(true);
          }, 100);
          newSelectedItems = prev;
        }
      }

      return newSelectedItems;
    });
  };

  /**
   * 触摸开始处理函数
   * 功能：记录触摸开始位置
   * 参数：e - 触摸事件对象
   * 返回值：无
   */
  const handleTouchStart = (e) => {
    setTouchStartY(e.touches[0].clientY);
  };

  /**
   * 触摸移动处理函数
   * 功能：记录触摸移动位置
   * 参数：e - 触摸事件对象
   * 返回值：无
   */
  const handleTouchMove = (e) => {
    setTouchEndY(e.touches[0].clientY);
  };

  /**
   * 触摸结束处理函数
   * 功能：检测向上滑动手势并切换页面
   * 参数：无
   * 返回值：无
   */
  const handleTouchEnd = () => {
    const swipeDistance = touchStartY - touchEndY;
    const minSwipeDistance = 50; // 最小滑动距离

    if (swipeDistance > minSwipeDistance && onNextPage) {
      onNextPage();
    }

    // 重置触摸位置
    setTouchStartY(0);
    setTouchEndY(0);
  };


  /**
   * 打包行李按钮点击处理函数
   * 功能：检查是否选择了5个行李，否则显示相应弹框
   * 参数：无
   * 返回值：无
   */
  const handlePackClick = async () => {
    console.log('点击打包行李，当前选择数量:', selectedItems.length);
    console.log('当前模式:', isGuessMode ? '猜行李模式' : '正常模式');
    console.log('shareUserId:', shareUserId);
    console.log('userOpenId:', userOpenId);
    console.log('selectedItems:', selectedItems);

    // 检查是否选择了5个行李
    if (selectedItems.length === 5) {
      if (isGuessMode) {
        // 猜行李模式：提交猜测结果
        console.log('猜行李模式：准备提交猜测结果');
        console.log('参数检查: shareUserId存在:', !!shareUserId, 'userOpenId存在:', !!userOpenId);
        await submitGuessResult();
      } else {
        // 正常模式：调用打包接口并保存数据
        console.log('选择了5个行李，调用打包接口');

        try {
          // 准备打包数据 - 获取选中物品的ID列表
          const selectedBaggageIds = selectedItems.map(index => {
            const item = itemsData[index];
            if (!item || !item.id) {
              console.warn('物品缺少ID:', item);
              return null;
            }
            return item.id;
          }).filter(id => id !== null).join(',');

          // 获取用户信息
          let openId = userOpenId || localStorage.getItem('openId') || '';
          let userId = '';  // 正常模式下不传 userId，或者传空

          // 确保 openId 不为空
          if (!openId || openId === '' || openId === 'null') {
            openId = 'fallback_openid_' + Date.now();
            localStorage.setItem('openId', openId);
            setUserOpenId(openId);
            console.log('使用备用 openId:', openId);
          }

          console.log('正常模式 - userId设为空字符串:', userId);

          console.log('使用的openId(优先从state):', openId);
          console.log('userOpenId state:', userOpenId);
          console.log('从localStorage获取的openId:', localStorage.getItem('openId'));
          console.log('从localStorage获取的userId:', userId);
          console.log('localStorage中所有的keys:', Object.keys(localStorage));

          const packagingData = {
            guessedBaggageIds: selectedBaggageIds, // 选中的行李ID列表（逗号分隔）
            matchScore: 0, // 正常打包模式默契度为0
            openId: openId,
            userId: userId // 用户ID或客户编号
          };

          console.log('准备提交的打包数据:', packagingData);
          console.log('packagingData.openId:', packagingData.openId);

          // 调用打包接口
          const response = await ApiService.luggage.getLuggageByUserId(packagingData);
          console.log('打包接口响应:', response);

          if (response.success || response.code === 200 || response.code === '200') {
            console.log('打包成功，保存数据到localStorage');

            // 保存打包行李数据到localStorage
            const packageData = {
              selectedItems: selectedItems,
              selectedBaggageIds: selectedBaggageIds,
              timestamp: new Date().getTime()
            };

            localStorage.setItem('package_data', JSON.stringify(packageData));
            console.log('打包行李数据已保存到localStorage:', packageData);

            // 跳转到textPage页面
            if (onGoToTextPage) {
              onGoToTextPage();
            }
          } else {
            console.error('打包失败:', response.message || '未知错误');
            alert(response.message || '打包失败，请重试');
          }
        } catch (error) {
          console.error('调用打包接口失败:', error);
          alert('打包失败，请检查网络连接');
        }
      }
    } else {
      console.log('未选择5个行李，显示打包失败弹框');
      setShowPackFailureModal(true);
    }
  };

  /**
   * 超出选择限制弹框关闭处理函数
   * 功能：关闭超出选择限制弹框
   * 参数：无
   * 返回值：无
   */
  const handleExceedLimitModalClose = () => {
    setShowExceedLimitModal(false);
  };

  return (
    <div
      className="fjyj-page"
      style={{
        backgroundImage: `url(${fjyjImg})`
      }}
    >
      <div
        className="fjyj-page-content"
      >
        <Header />

        <img src={cc2026Img} alt="fz" className="cc2026-img" />


        {/* xzbjt 背景图片容器 - 宽度90%居中显示 */}
        <div
          className="xzbjt-container"
          style={{
            backgroundImage: `url(${xzbjtImg})`
          }}
        >
          <img src={bzImg} alt="xzbjt" style={{ width: '20px', height: '30px', position: 'absolute', top: '-13px', right: '30px' }} />
          <div className='xzbjt-btn-content'>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div className="icon-btn-container" onClick={handlePackClick} style={{ cursor: 'pointer' }}>
                {isGuessMode ? '猜行李' : '选择行李'}
              </div>
              <div className='xzbjt-text'>
                {isGuessMode ? '请猜猜TA选择了哪五个行李' : '请选择五个行李'}
              </div>
            </div>
            <div className='xzbjt-count'>{selectedItems.length}/5</div>
          </div>

          <div className='icon-grid'>
            {/* 图标网格容器 - 3行5列布局 */}
            {isLoadingItems ? (
              <div style={{ textAlign: 'center', padding: '20px', color: '#666' }}>
                加载中...
              </div>
            ) : (
              Array.from({ length: 3 }, (_, rowIndex) => (
                <div key={rowIndex} className="icon-grid-row">
                  {Array.from({ length: 5 }, (_, colIndex) => {
                    const itemIndex = rowIndex * 5 + colIndex;
                    const currentItem = itemsData[itemIndex];

                    // 如果没有对应的物品数据，不显示该项
                    if (!currentItem) {
                      return (
                        <div key={colIndex} className="icon-item-empty"></div>
                      );
                    }

                    return (
                      <div
                        key={colIndex}
                        className="icon-item"
                        style={{
                          backgroundImage: `url(${iconBackImg})`
                        }}
                        onClick={() => handleIconClick(itemIndex)}
                      >
                        <div className='icon-img' style={{
                          backgroundImage: `url(${currentItem.picurl || currentItem.img || currentItem.image || imagesText[itemIndex]?.img})`
                        }}></div>
                        <div className='icon-text'>{currentItem.name || currentItem.text || imagesText[itemIndex]?.text}</div>

                        {/* 圆形选择框 - 显示勾选状态 */}
                        <div className={`selection-circle ${selectedItems.includes(itemIndex) ? 'selected' : ''}`}>
                          {selectedItems.includes(itemIndex) && (
                            <img src={gxImg} alt="已选中" className="checkmark-icon" />
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              ))
            )}
          </div>

          <div className='dbxlImage-img' alt="打包行囊" onClick={handlePackClick} style={{ cursor: 'pointer' }}>
            {isGuessMode ? '提交猜测' : '选好了'}
          </div>
        </div>


        {/* 打包行李弹框组件 */}
        {showPackModal && (
          <div className="modal-overlay" onClick={handlePackModalClose}>
            <div
              className="modal-content"
              style={{
                backgroundImage: `url(${dbxlBackImg})`,
                width: '90%',
                height: '200px',
                backgroundSize: '100% 100%',
                backgroundPosition: 'center',
                backgroundRepeat: 'no-repeat'
              }}
              onClick={(e) => e.stopPropagation()}
            >
              <div className="modal-close-btn" onClick={handlePackModalClose}>
                <img src={closeImg} alt="关闭" style={{ width: '100%', height: '100%' }} />
              </div>
              <div className="modal-body" style={{ 
                display: 'flex', 
                flexDirection: 'column', 
                alignItems: 'center', 
                height: '100%',
                color: '#333',
                padding: '0px',
                marginTop: '10px'
              }}>
                <div style={{ 
                  fontSize: '34px', 
                  fontWeight: 'bold', 
                  marginBottom: '20px',
                  textAlign: 'center',
                  color: '#fff'
                }}>
                  我的行囊
                </div>
                <div style={{ 
                  fontSize: '16px', 
                  textAlign: 'center',
                  lineHeight: '1.5'
                }}>
                  {/* 已选择的行李展示区域 */}
                  <div className='icon-grid-select' style={{ 
                    display: 'flex', 
                    justifyContent: 'center',
                    gap: '0.7px',
                    marginTop: '10px'
                  }}>
                    {selectedItems.map((itemIndex) => {
                      const currentItem = itemsData[itemIndex] || imagesText[itemIndex] || {};
                      return (
                        <div
                          key={itemIndex}
                          className="icon-item"
                          style={{
                            backgroundImage: `url(${iconBackImg})`,
                            width: '65px',
                            height: '65px',
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            justifyContent: 'center',
                            position: 'relative'
                          }}
                        >
                          <div className='icon-img' style={{
                            backgroundImage: `url(${currentItem.picurl || currentItem.img || currentItem.image})`,
                            width: '30px',
                            height: '30px',
                            backgroundSize: 'contain',
                            backgroundRepeat: 'no-repeat',
                            backgroundPosition: 'center'
                          }}></div>
                          <div className='icon-text' style={{
                            fontSize: '10px',
                            color: '#333',
                            textAlign: 'center',
                            marginTop: '2px'
                          }}>{currentItem.name || currentItem.text}</div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 打包失败弹框组件 */}
        <PackFailureModal
          isVisible={showPackFailureModal}
          onClose={handlePackFailureModalClose}
        />

        {/* 超出选择限制弹框组件 */}
        {showExceedLimitModal && (
          <div className="pack-failure-modal-overlay" onClick={handleExceedLimitModalClose}>
            <div
              className="pack-failure-modal-content"
              onClick={(e) => e.stopPropagation()}
              style={{
                backgroundImage: `url(${xyImg})`,
                backgroundSize: '100% 100%',
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'center'
              }}
            >
              {/* 提示内容 */}
              <div className="pack-failure-content">
                <div className="pack-failure-title">
                  已选择5个
                </div>
                <div className="pack-failure-message">最多只能选择5个行李</div>
                <div className="pack-failure-confirm-btn" onClick={handleExceedLimitModalClose}>
                  确定
                </div>
              </div>
            </div>
          </div>
        )}


      </div>
    </div>
  );
};

export default FjyjPage;